package com.wlzg.collectiontool.view

import android.Manifest
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.os.Environment.getExternalStorageDirectory
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.PolylineBuilder
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.LocationDisplay
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.github.dfqin.grantor.PermissionListener
import com.lxj.xpopup.XPopup
import com.wlzg.collectiontool.R
import com.wlzg.collectiontool.map.TianDiTuTiledLayerClass
import com.wlzg.collectiontool.util.ExcelUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.text.NumberFormat


class CollectionActivity : BaseActivity(), View.OnClickListener {
    private val TAG: String = "CollectionActivity"
    private var addPointModel = false
    private var addLineModel = false
    private var locationDisplay: LocationDisplay? = null
    private val linePoints by lazy { ArrayList<Point>() }
    private val graphicsOverlay by lazy { GraphicsOverlay() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        init()
        initPermissions()
        initMap()
        initListener()
    }

    private fun init() {
        guandian.setOnClickListener(this)

    }

    private fun initListener() {
        mapView.onTouchListener = object : DefaultMapViewOnTouchListener(this, mapView) {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                if (mapView.callout != null && mapView.callout.isShowing) {
                    mapView.callout.dismiss()
                }
                if (addPointModel) {
                    val point =
                        android.graphics.Point(e.x.toInt(), e.y.toInt())
                    val point1: Point = mapView.screenToLocation(point)
                    Log.e("test", point1.toString())
                    // 生成一个红色圆形标识
                    val pointSymbol = SimpleMarkerSymbol(
                        SimpleMarkerSymbol.Style.CIRCLE,
                        Color.RED,
                        10F
                    )
                    val graphic = Graphic(point1, pointSymbol)
                    graphic.attributes["value"] = "graphic：${(Math.random() * 10).toInt()}"
                    graphicsOverlay.graphics.add(graphic)
                } else if (addLineModel) {
                    val point =
                        android.graphics.Point(e.x.toInt(), e.y.toInt())
                    val point1: Point = mapView.screenToLocation(point)
                    linePoints.add(point1)
                    if (linePoints.size == 1) {
                        val pointSymbol = SimpleMarkerSymbol(
                            SimpleMarkerSymbol.Style.SQUARE,
                            Color.BLUE,
                            5F
                        )
                        val graphic = Graphic(point1, pointSymbol)
                        graphicsOverlay.graphics.add(graphic)
                    } else {
                        graphicsOverlay.graphics.clear()
                    }
                    val lineGeometry = PolylineBuilder(mapView.spatialReference)
                    lineGeometry.addPoints(linePoints)
                    val lineSymbol = SimpleLineSymbol(
                        SimpleLineSymbol.Style.SOLID,
                        Color.BLUE,
                        5F
                    )
                    val length = GeometryEngine.length(lineGeometry.toGeometry())
                    val numberFormat = NumberFormat.getInstance()
                    numberFormat.maximumFractionDigits = 2
                    val s = numberFormat.format(length)
                    val lineGraphic = Graphic(lineGeometry.toGeometry(), lineSymbol)
                    lineGraphic.attributes["value"] = "长度：$s 米"
                    graphicsOverlay.graphics.add(lineGraphic)

                }

                return super.onSingleTapConfirmed(e)
            }
        }
    }

    private fun initPermissions() {
        requestPermission(this, arrayOf<String>(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ), object :
            PermissionListener {
            override fun permissionGranted(permission: Array<out String>) {
                var list: Array<String?> = Array(1, { "mytest" })
                var objList: ArrayList<ArrayList<String>> = ArrayList()
                var delist: ArrayList<String> = ArrayList()
                delist.add("name")
                delist.add("jsjsj")
                delist.add("name")
                delist.add("jsjsj")
                objList.add(delist)
                objList.add(delist)
                objList.add(delist)

//                GlobalScope.launch {
//                    var excel = ExcelUtils()
//                    excel.initExcel(
//                        getExternalStorageDirectory().absolutePath + "/testss.xls",
//                        list
//                    )
//                    excel.writeObjListToExcel(
//                        objList,
//                        getExternalStorageDirectory().absolutePath + "/testss.xls",
//                        this@CollectionActivity
//                    )
//                    excel.readExcelToDB()
//
//                }
            }

            override fun permissionDenied(permission: Array<out String>) {
                for (i in permission) {
                    Log.d(TAG, i)
                }
            }
        })
    }

    private fun initMap() {
        ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud4449636536,none,NKMFA0PL4S0DRJE15166")
        mapView.isAttributionTextVisible = false
        //默认底图
        val webTiledLayer =
            TianDiTuTiledLayerClass.CreateTianDiTuTiledLayer(
                TianDiTuTiledLayerClass.LayerType.TIANDITU_VECTOR_MERCATOR
            )
        //标注
        val webTiledLayerLable =
            TianDiTuTiledLayerClass.CreateTianDiTuTiledLayer(
                TianDiTuTiledLayerClass.LayerType.TIANDITU_VECTOR_MERCATOR_LABLE
            )
        val basemap = Basemap()
        basemap.baseLayers.add(webTiledLayer)
        basemap.baseLayers.add(webTiledLayerLable)
        val arcGISMap = ArcGISMap(basemap)
        mapView.map = arcGISMap
        mapView.graphicsOverlays.add(graphicsOverlay)
//        mapView.graphicsOverlays.add(queryBoxOverlay)

        //定位
        locationDisplay = mapView.locationDisplay//获取定位类
        locationDisplay?.isShowLocation = true
        locationDisplay?.isShowPingAnimation = true
        locationDisplay?.isShowAccuracy = true
        locationDisplay?.autoPanMode = LocationDisplay.AutoPanMode.OFF  //设置模式
        locationDisplay?.startAsync()//开始定位

//        tvScale.text = "${mapView.mapScale}"
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.guandian -> {

            }
        }
    }


}